<template>
  <div id="index">
    <Header left="arrow" title="客服" right="ellipsis"></Header>
    <div class="body" ref="body">
      <div v-for="(item,index) in msgs" :key="index">
        <!-- <div v-if="item.msgType=='online'" class="onlineMsg">
          <div class="sysTime">{{item.now_date}}</div>
          <div class="online">上线</div>
        </div>
        <div v-else-if="item.msgType=='offline'" class="offlineMsg">
          <div class="sysTime">{{item.now_date}}</div>
          <div class="online">下线</div>
        </div>-->
        <div class="clientMsg">
          <div class="sysTime">{{formatDate(item.now_date)}}</div>
          <!-- 自己发出的 -->
          <div v-if="item.sendTo != user_id" class="self">
            <div class="bubble">
              <div class="chatBubble">{{item.the_message}}</div>
              <div class="triangle"></div>
            </div>
            <div class="user"></div>
          </div>
          <!-- 他人发出的 -->
          <div v-else class="others">
            <div class="user"></div>
            <div class="bubble">
              <div class="chatBubble">{{item.the_message}}</div>
              <div class="triangle"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="footer">
      <div class="msgInput">
        <van-icon color="#333333" class="msg-icon-left" name="comment-circle-o" />
        <input
          v-model="msg"
          autofocus
          class="input"
          type="text"
          @keydown.enter="websocketsend(msg)"
          placeholder
        />
        <van-icon name="smile-o" class="msg-icon-right" />
        <van-icon name="add-o" class="msg-icon-right" />
      </div>
    </div>
  </div>
</template>

<script>
import Header from "../../components/Header";
import Vue from "vue";
// import chatApi from "@/api/chat";
import { NavBar } from "vant";

Vue.use(NavBar);
export default {
  name: "chatRoom",
  components: {
    Header,
  },
  data() {
    return {
      title: "客服",
      socket: null,
      msg: "",
      msgs: [],
      clientNum: "123",
      showEmoji: false,
      emoji: [],
      user_id: localStorage.getItem("user_id"),
      sendTo: ""
    };
  },
  created() {
    this.sendTo = this.$route.query.user_id;
    // this.fetchData();
    // this.initWebSocket();
    window.addEventListener("scroll", this.changePopStyle, true);
  },
  mounted() {
    this.$nextTick(() => {
      this.autoScrollToBottom();
    });
  },
  beforeDestroy() {
    window.removeEventListener("scroll", this.changePopStyle, true);
    this.socket.close();
  },
  methods: {
    //处理时间戳
    formatDate(v) {
      var value = Number(v)
      var date = new Date(value);
      var year = date.getFullYear();
      /* 在日期格式中，月份是从0开始的，因此要加0
       * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
       * */
      var month =
        date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1;
      var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      var hours =
        date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
      var minutes =
        date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
      var second =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      // 拼接
      return (
        year +
        "-" +
        month +
        "-" +
        day +
        " " +
        hours +
        ":" +
        minutes +
        ":" +
        second
      );
    },
    //自动滑倒底部
    autoScrollToBottom() {
      this.$refs.body.scrollTop = this.$refs.body.scrollHeight;
    },
    //滚动监听
    changePopStyle() {
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      console.log("滚动监听", scrollTop);
    },
    //WebSocket初始化
    initWebSocket() {
      this.socket = this.$socket;
      this.socket.onmessage = this.websocketonmessage;
      this.socket.onopen = this.websocketonopen;
      this.socket.onerror = this.websocketonerror;
      this.socket.onclose = this.websocketonclose;
    },
    websocketonmessage(e) {
      console.log("WebSocket取得返回数据：", e.data);
      var res = JSON.parse(e.data);
      this.msgs.push({
        now_date: res.now_date,
        the_message: res.the_message,
        sendTo: res.sendTo,
        getFrom: res.getFrom
      });
      this.$nextTick(() => {
        this.autoScrollToBottom();
      });
    },
    websocketonopen() {
      console.log("WebSocket连接建立成功！");
    },
    websocketonerror() {
      console.log("WebSocket is error");
    },
    websocketonclose(e) {
      console.log("WebSocket is close", e);
    },
    //数据发送
    websocketsend(data) {
      var transdata = {
        the_message: data,
        sendTo: this.sendTo,
        imageName: ""
      };
      console.log("发送的数据：", transdata);
      if (data) {
        this.$socket.send(JSON.stringify(transdata));
        console.log("数据发送成功");
        this.msgs.push({
          now_date: new Date().getTime(),
          the_message: data,
          sendTo: this.sendTo,
          getFrom: localStorage.getItem("user_id"),
          isNew: true
        });
        this.msg = "";
      } else {
        alert("消息为空！");
      }
      this.$nextTick(() => {
        this.autoScrollToBottom();
      });
    },

    //导航栏左边按钮
    onClickLeft() {
      this.$router.go(-1);
    },
    //导航栏右边按钮
    onClickRight() {},
    //取得模拟数据
    fetchData() {
      var formData = new FormData();
      formData.append("getFrom", this.sendTo);
    //   chatApi.chat_getAllMessage(formData).then(response => {
    //     console.log(response.data);
    //     this.msgs = response.data;
    //     this.$nextTick(() => {
    //       this.autoScrollToBottom();
    //     });
    //   });
      // this.msgs.push(
      //   {
      //     time: "15.22.24",
      //     username: "user1",
      //     msgType: "offline",
      //     msg: "我是测试用户"
      //   }
      // );
    }
  }
};
</script>

<style scoped>
a {
  text-decoration: none;
}
a:hover {
  color: brown;
}
#index {
  position: fixed;
  padding-top: 2.13rem;
  height: 100%;
  margin-bottom: 1.3rem;
  background-color: #f5f5f5;
}
.header {
  position: fixed;
  height: 2.13rem;
  line-height: 1.457rem;
  left: 0px;
  top: 0px;
  right: 0px;
  z-index: 1;
}
.icon_font {
  font-size: 18px;
}
::v-deep [class*="van-hairline"]::after {
  border: 0 solid #ebedf0;
}
.header_left {
  color: #fff;
}
.header_right {
  font-size: 15px;
  color: #333;
}
.header_title {
  font-size: 15px;
  color: #333;
  height: 2.13rem;
  line-height: 2.803rem;
}
.van-nav-bar {
  background-color: #f5f5f5;
}
.body {
  position: fixed;
  top: 2.13rem;
  bottom: 1.3rem;
  width: 100%;
  overflow: auto;
  text-align: center;
}
.iconfont {
  font-size: 24px;
}
.logout,
.about {
  padding: 7px;
}
.sysTime {
  color: #999;
  font-size: 13px;
  margin-bottom: 3px;
}
.onlineMsg,
.offlineMsg,
.clientMsg {
  margin-bottom: 10px;
  height: 50px;
  width: 100%;
}
.clientMsg {
  position: relative;
}
.online,
.offline {
  display: inline-block;
  height: 23px;
  padding-left: 10px;
  padding-right: 10px;
  border-radius: 3px;
  color: #999;
  text-align: center;
  line-height: 23px;
  background-color: rgb(209, 209, 209);
  font-size: 16px;
  box-sizing: border-box;
}
.self {
  position: absolute;
  right: 14px;
}
.others {
  position: absolute;
  left: 14px;
}
.bubble {
  display: inline-block;
  position: relative;
}
.chatBubble {
  height: 30px;
  line-height: 30px;
  background-color: rgb(198, 205, 243);
  font-size: 16px;
  color: rgb(58, 58, 58);
  border-radius: 10px;
  padding-left: 10px;
  padding-right: 10px;
}
.self .triangle {
  position: absolute;
  right: -10px;
  top: 10px;
  border-left: 10px solid rgb(198, 205, 243);
  border-bottom: 10px solid transparent;
}
.others .triangle {
  position: absolute;
  left: -10px;
  top: 10px;
  border-right: 10px solid rgb(198, 205, 243);
  border-bottom: 10px solid transparent;
}
.self .user {
  display: inline-block;
  margin-left: 10px;
}
.others .user {
  display: inline-block;
  margin-right: 10px;
  font-size: 12px;
}
.footer {
  height: 1.3rem;
  width: 100%;
  position: fixed;
  bottom: 0;
  position: fixed;
  display: flex;
  background-color: #f0f0f0;
}
.emoji {
  position: absolute;
  left: 10px;
  top: 10px;
}
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter,
.fade-leave-to {
  opacity: 0;
}
.emojiList {
  display: inline;
  /* width: 400px;
  height: 145px; */
  position: absolute;
  bottom: 30px;
  border: 1px solid #ccc;
  background-color: rgb(244, 248, 250);
  box-sizing: border-box;
  padding: 0px;
}
.emojiList li {
  display: inline-block;
  margin: 0;
  cursor: pointer;
  width: 24px;
  height: 24px;
  box-sizing: border-box;
}
.emojiList li:hover {
  border: 1px solid #ccc;
}
.msgInput {
  position: relative;
  width: 100%;
  height: 0.9rem;
  line-height: 0.9rem;
  margin-top: 0.1777rem;
  padding-left: 3vw;
}
.msgInput .input {
  box-sizing: border-box;
  width: 70vw;
  height: 0.9rem;
  border: 1px solid #eee;
  padding-left: 2vw;
  background-color: white;
  font-size: 18px;
  caret-color: #c6cdf3;
  color: #333333;
  margin-left: 2vw;
}
.msg-icon-left {
  font-size: 24px;
  position: relative;
  top: 0.1777rem;
  /* color: #333333; */
}
.msg-icon-right {
  font-size: 24px;
  position: relative;
  top: 0.1777rem;
  /* color: #333333; */
  margin-left: 1.7vw;
}
</style>
